package IEFYP.JunkCallFiltering;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;



import IEFYP.JunkCallFiltering.ReportJunkCall.CallInfo;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;


/*
 * two case:
 * 1. report the blocked call
 * 2. report the calls without Internet service or server not ready;
 * 
 * 
 * 
 */
public class AutoReport extends Service{
	private static String Networkstatus = null;
	public final static String ACTION = "Start Auto-reporting service";
	private final String Tag = "AutoReport";
    private boolean threadDisable;
    private AutoReportReceiver receiver;
    private int count;
    public  boolean running;
    

    private ServiceBinder serviceBinder=new ServiceBinder();

    public class ServiceBinder extends Binder{// implements ICountService{
     /*   @Override
        public int getCount() {
            return count;

        }*/

    }
    
    
  
   
	public void report(reportedCall call){
		
				Log.v(Tag, "Reporting!" );
	   			 DefaultHttpClient client =  ReportJunkCall.setupHttpClient();
	   			 
		    //	String url = "http://192.168.172.130/collectcalls.php?callno="+callno+"&btype=\""+btype+"\"&callchar=\""+callchar+"\"&datetime="+time.format2445();
			//	HttpGet request = new HttpGet(url);
		    	String url = "http://"+ReportJunkCall.ServerIp+"/collectcalls.php";
		    	HttpPost request = new HttpPost(url);
		    	try{
			    		
			    		//String url = "http://192.168.172.130/collectcalls.php?callno="+callno+"&btype="+btype+"&callchar="+callchar+"&datetime="+time.format2445();
			    		List<NameValuePair> postValues = new ArrayList<NameValuePair>();
			    		postValues.add(new BasicNameValuePair("callno",call.Callno));
			    	//	postValues.add(new BasicNameValuePair("datetime",ReportTime.format2445()));//report date
			    		postValues.add(new BasicNameValuePair("datetime",call.IncomingDatetime)); //incure date	
			    		if(call.Char!=null){postValues.add(new BasicNameValuePair("callchar",call.Char));}
			    		if(call.Type!=null){postValues.add(new BasicNameValuePair("btype",call.Type));}
			    	
			    		request.setEntity(new UrlEncodedFormEntity(postValues));
			    		//Toast.makeText(ReportJunkCall.this,"Successfully reported!!",Toast.LENGTH_SHORT).show();
			    		HttpResponse response = client.execute(request);
			   			if(response.getStatusLine().getStatusCode()==200){
			   				Toast.makeText(AutoReport.this,
			   						"Successfully reported!!\n"
			   						+"Number: "+ call.Callno 
			   						+"\nIncomingTime:"+call.IncomingDatetime,
			   						Toast.LENGTH_SHORT).show(); 			   				
			   				getContentResolver().delete(android.provider.CallLog.Calls.CONTENT_URI,android.provider.CallLog.Calls.NUMBER+"='"+call.Callno+"'" , null);					   		
			   				Log.v(Tag, "Reported!" );
			   			}
		 }catch (Exception e){
   		//	 Toast.makeText(AutoReport.this,e.toString(),200).show(); 
   			Log.v(Tag, "Fail!!" );
   	
  			 Log.v(Tag,e.getMessage());
  			 if(ReportJunkCall.isOnline(AutoReport.this)){
  				Toast.makeText(AutoReport.this,"Server is unavailable!",200).show(); 
  				Log.v(Tag," server unavailable! ");
  				// Try to send again every 3 hours;
  				
  			 }else{
  				Log.v(Tag," No Internet service! ");
  				Toast.makeText(AutoReport.this,"No Internet service!",200).show(); 
  				//Try to send until the Internet service is available// add to database
  			 }
  			 

   		 }
	}
			   		  
    
    protected class reportedCall {
    	public String Callno;
    	public String IncomingDatetime;
    	public String Duration;
    	public String Type;
    	public String Char;
    	
    	public reportedCall(){
    		Duration = null;
    		Type = null;
    		Char = null;
    	}
    }
    
    public class AutoReportReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			reportedCall call = new reportedCall();
			call.Callno = intent.getExtras().getString("callno");
			call.IncomingDatetime = intent.getExtras().getString("time");
			report(call);	
			Log.v(Tag, "Broadcast receiver work!" );
		}
    	
    		
    }

    @Override

    public IBinder onBind(Intent intent) {
        return serviceBinder;
    }
// looping until 
    @Override
    public void onCreate() {
        super.onCreate();
        receiver = new AutoReportReceiver();
        IntentFilter filter = new IntentFilter(AutoReport.ACTION);	
		registerReceiver(receiver, filter);	
		
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (!threadDisable) {
                    try {
                        Thread.sleep(10*1000);
                    } catch (InterruptedException e) {
                    }
                    count++;
                  //  Log.v("CountService", "Count is " + count);
                }
            }
        }).start();
        
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
        unregisterReceiver(receiver); 		//Unregister Receiver
        Log.v("CountService", "on destroy");
    }

    /* (non-Javadoc)
     * @see com.easymorse.ICountService#getCount()
     */
    public int getCount() {
        return count;
    }

}
